/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network.socketprogram;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author anh_yeu_em_nhieu_lam
 */
public class Server extends Thread {

    private ServerSocket serverSocket;
    public Server() {
        try {
            serverSocket = new ServerSocket(1986);//Tạo server socket ở cổng 1986
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        try {
            //Mỗi user kết nối đến tạo một luồng xử lý
            ClientConnect newconnect = new ClientConnect(serverSocket.accept());
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //
    public class ClientConnect extends Thread{
        private ObjectInputStream input;
        private ObjectOutputStream output;
        private Socket ssocket;
        private String message;
        public ClientConnect(Socket serverSocket) throws IOException {
            this.ssocket = serverSocket;
            input = new ObjectInputStream(ssocket.getInputStream());
            output = new ObjectOutputStream(ssocket.getOutputStream());
            this.start();
        }
        @Override
        public void run() {
            while(true){
                try {
                    message = (String) input.readObject();
                    System.out.print("Client send message : "+message);
                    output.writeObject("Server da nhan duoc thong diep \"" + message+"\"");
                } catch (IOException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }

    public static void main(String[] args) {
        new Server().start();
    }
}
